package group32.client;
import group32.shared.User;

import java.sql.ResultSet;
import java.text.SimpleDateFormat;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CaptionPanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.xml.client.Node;

public class UserProfile extends Composite implements ValueChangeHandler<String>{
	//int userid=-1;
	private UserProfileServiceAsync pService = GWT
	.create(UserProfileService.class);
	
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";
	
	private JavaScriptObject theGraph;
	public static int friendID;
	
	VerticalPanel hp = new VerticalPanel();
	VerticalPanel dummy= new VerticalPanel();
	VerticalPanel searchPanel = new VerticalPanel();
	HorizontalPanel mainPanel= new HorizontalPanel();
	VerticalPanel LeftPanel = new VerticalPanel();
	VerticalPanel RightPanel = new VerticalPanel();
	VerticalPanel upLeftPanel = new VerticalPanel();
	VerticalPanel upRightPanel = new VerticalPanel();
	VerticalPanel photoPanel = new VerticalPanel();
	HorizontalPanel h1= new HorizontalPanel();
		VerticalPanel v1 = new VerticalPanel();
		VerticalPanel v2 = new VerticalPanel();
	HorizontalPanel h2= new HorizontalPanel();
	HorizontalPanel search= new HorizontalPanel();
	TextBox searchField = new TextBox();
	Button bSearch= new Button();
	Hyperlink logOff = new Hyperlink("Logout", "logout");
	Hyperlink friends = new Hyperlink("Friends","friends");
	Hyperlink circles = new Hyperlink("Circles","circles");
	Hyperlink photos = new Hyperlink("Photos", "photos");
	Hyperlink home = new Hyperlink("Home", "HomePage");
	VerticalPanel sp= new VerticalPanel();
	VerticalPanel sr= new VerticalPanel();	 
	final Label nameLabel = new Label("");
	  final Label titleLabel = new Label("");
	  final Label emailLabel = new Label("");
	  final Label dobLabel = new Label("");
	  final Label genderL = new Label("");
	  final Label addressL = new Label("");
	  final Label schoolL = new Label("");
	  final Label gpaL = new Label("");
	  final Label majorL = new Label("");
	  final Label yearL = new Label("");
	  final Label roomL = new Label("");
	  final Label researchL = new Label("");
	  final Label adviseL = new Label("");
	  final Label adinfoL = new Label("");
	  final Label interestL = new Label("");
	  final Label errorL = new Label("");
	  public String utype="";
	  public int userid=0;
	  public String login="";
	  @SuppressWarnings("deprecation")
	static ClickListener listner;
	  static DialogBox dialogBox;

	Hyperlink edit = new Hyperlink("Update Profile Details", "edituser");
	Hyperlink editSec = new Hyperlink("Update Credentials","editsecurity");
	  
	/**
	 * This is the entry point method.
	 */
	public UserProfile(final int uid,String type,final int friendID,final String username,int sender) {
		photos.setVisible(false);
		userid=0;
		login="";
		utype="";
		
		userid=uid;
		login=username;
		utype=type;

		System.out.println("Userpage uid:"+ uid);
		System.out.println("Userpage username:"+ username);
		History.addValueChangeHandler(this);

			
			//hp.setHeight("700px");
			searchPanel.setVerticalAlignment(HorizontalPanel.ALIGN_BOTTOM);

			searchPanel.setHeight("100px");
			searchPanel.setWidth("910px");
			bSearch.setText("Search");
			//v1.setHorizontalAlignment(VerticalPanel.ALIGN_LEFT);
			//v2.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
			v1.add(new Label("Welcome "+username));v2.add(logOff);
			h1.setSpacing(10);
			h2.setSpacing(2);
			h2.add(v1);h2.add(v2);
			h1.add(circles);h1.add(friends);h1.add(photos);
			h1.add(editSec);h1.add(edit);h1.add(home);
			searchField.setWidth("350px");
			search.setSpacing(10);
			search.add(searchField);search.add(bSearch);
			h1.add(search);
			h1.setVerticalAlignment(HorizontalPanel.ALIGN_BOTTOM);
			h1.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
			searchPanel.add(h2);
			searchPanel.add(h1);
			if(sender!=2)
			hp.add(searchPanel);
		
		LeftPanel.setHeight("550px");
		LeftPanel.setWidth("550px");
		LeftPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		LeftPanel.setVerticalAlignment(VerticalPanel.ALIGN_BOTTOM);
			photoPanel.setWidth("550px");
			photoPanel.setHeight("225px");
		RightPanel.setHeight("550px");
		RightPanel.setWidth("500px");
		RightPanel.setVerticalAlignment(VerticalPanel.ALIGN_BOTTOM);
		
		History.newItem("userprofile");
		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		Window.setTitle("User Profile");
		
		RightPanel.setSpacing(5);
		//RightPanel.add(new Label("<div>"));
		getUser(uid,type);
		 // RightPanel.add(new Label("</div>"));
			mainPanel.add(RightPanel);
			photoPanel.setStyleName(".paddedHorizontalup");
			if (sender!=2){
		photoPanel.add(new Photo(userid, login, 1));
			}
			else {
				photoPanel.add(new Photo(userid,friendID, login,0));
			}
		LeftPanel.add(photoPanel);
		mainPanel.add(LeftPanel);
			
			//updatePanel.add(sp);

			//mainPanel.setBorderWidth(1);
		
		hp.setVerticalAlignment(VerticalPanel.ALIGN_BOTTOM);
		hp.add(mainPanel);
		initWidget(hp);

		bSearch.addClickHandler(new ClickHandler() {
	        public void onClick(ClickEvent event) {
	        	String keys= searchField.getValue();
	        	if(keys.trim().length()>1)
	        	 FlowControl.go(new Search(keys,uid)); 
	        }
	    });
		
		dialogBox = new DialogBox(false);
		dialogBox.setHeight("200px");
		dialogBox.setTitle("Update Security Credentials");
		dialogBox.setStyleName("table-center");
		dialogBox.setAnimationEnabled(true);	 
		
		listner= new ClickListener() {
			
			@Override
			public void onClick(Widget sender) {
				dialogBox.hide();
			}
		};
		
		final Button closeButton = new Button("Close",listner);
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.add(new EditSecurity(userid, login));
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);
	
		 listner= new ClickListener() {
			
			@Override
			public void onClick(Widget sender) {
				dialogBox.show();
				dialogBox.center();
			}
		};
		
		editSec.addClickListener(listner);
		
		
	}
	
	@SuppressWarnings("rawtypes")
	public void onValueChange(ValueChangeEvent event){
		if(History.getToken().equals("edituser"))
			FlowControl.go(new EditProfile(utype,userid,login));
		if(History.getToken().equals("circles"))
            FlowControl.go(new Circle(userid,login));            
		if(History.getToken().equals("photos"))
            FlowControl.go(new Photo(userid,login,0)); 
		if(History.getToken().equals("logout"))
	        FlowControl.go(new Login());    
		if(History.getToken().equals("HomePage"))
	        FlowControl.go(new HomePage(userid,login));    
	}
	
	//public void updateSecurity(){
	

	//}
	
	public String greetServer(String name) throws IllegalArgumentException {
		// TODO Auto-generated method stub
		return null;
	}
	  
	public User getUser(int userID,String usertype) {
		  // TODO Auto-generated method stub
          pService.getUser(userID,usertype, new AsyncCallback<User>()  {
                  public void onSuccess(User u) {
                	  if(u!=null){
                		  System.out.println(u.email);
                		  utype=Character.toString(u.usertype);
                		  if(u.title!=null)
                			  nameLabel.setText("Name: "+u.firstname+" "+u.lastname+" ("+u.title+")");
                		  else
                			  nameLabel.setText("Name: "+u.firstname+" "+u.lastname);
                		  RightPanel.add(nameLabel); 
                		  emailLabel.setText("Email: "+u.email);
                		  RightPanel.add(emailLabel); 
                		  if(u.dob!=null){ 
                			  DateTimeFormat fmt = DateTimeFormat.getFormat("MMMM d, yyyy");
							String sb= fmt.format(u.dob,null);
                		  dobLabel.setText("Birthdate: "+sb);
                		  RightPanel.add(dobLabel);
                		  }
                		  if(u.gender!=' '){
                		  String g;
                		  if(u.gender=='M')
                			  g="Male";
                		  else
                			  g="Female";
                		  genderL.setText("Gender: "+g);
                		  RightPanel.add(genderL);
                		  }
                		  if(u.address!=null){
                		  addressL.setText("Address: "+u.address);
                		  RightPanel.add(addressL);
                		  }
                		  if(u.school!=null){
                		  schoolL.setText("Academic Institution: "+u.school);
                		  RightPanel.add(schoolL);
                		  }
                		  if(u.major!=null){
                		  majorL.setText("Major: "+u.major);
                		  RightPanel.add(majorL);
                		  }
                		  if(u.year!=0){
                     		  yearL.setText("Year: "+Integer.toString(u.year));
                     		  RightPanel.add(yearL);
                		  }
                		  if(u.GPA!=0){
                		   String formatted = NumberFormat.getFormat("0.00").format(u.GPA);
                		  gpaL.setText("GPA: "+formatted);
                		  RightPanel.add(gpaL);
                		  }
                		  if(u.advisor!=null){
                		  adviseL.setText("Advisor: "+u.advisor);
                		  RightPanel.add(adviseL);
                		  }
                		  if(u.usertype!=' '){
                			  if(u.usertype=='S'){
                				  if(u.yearsAdvised!=0){
                        		  adinfoL.setText("Years advised: "+Integer.toString(u.yearsAdvised));
                        		  RightPanel.add(adinfoL);
                				  }
                			  }
                			  else{
                				  if(u.advises!=0){
                            		  adinfoL.setText("#Students advised: "+Integer.toString(u.advises));
                            		  RightPanel.add(adinfoL);
                				  }
                			  }
                		  }
                		  if(u.interests!=null){
                			  int b=0;
                			  if(u.interests.length()>=1){
                			  b=u.interests.length()-1;
                    		  interestL.setText("Likes/Interests: "+u.interests.substring(0,b));
                    		  RightPanel.add(interestL);
                			  }
                		  }
                		  
                		  if(u.roomNumber!=0){
                    		  roomL.setText("Room Number: "+Integer.toString(u.roomNumber));
                    		  RightPanel.add(roomL);
                		  }
                		  
                		  if(u.researchArea!=null){
                    		  researchL.setText("Research Areas: "+u.researchArea);
                    		  RightPanel.add(researchL);
                		  }
                	  }
                		  
                  }
                  
                  public void onFailure(Throwable caught) {
                	//do nothing
                	  errorL.setText("Database error");
                	  RightPanel.add(errorL);
                  }
                 
                 
          }); return null;
	}

	
}
